<?php
namespace app\api\controller;

use think\Cookie;
use think\Exception;
use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;
use ucpaas\SendMsg;
use \think\Validate;
use Common\Oss;

class User extends Base
{
    /**
     * @writer:leijie
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 用户注册
     * @return array|Json
     */
    public function registered(){
        $data = Request::instance()->post();
        // 判断手机号是否已注册
        $phoneNum   = $data['account'];
        $user       = Db::table('user')->where(['account'=>$phoneNum])->count();
        $supplier   = Db::table('supplier')->where('account',$phoneNum)->count();
        if ($user>0){
            $result = Config::get('code.error');
            $result['msg'] = "该手机号已注册账号，请使用手机号登录";
        }else if($supplier >0){
            $result = Config::get('code.error');
            $result['msg'] = "手机号已在商户端注册，不能再次注册";
        }else{
            try{
                $code = $data['code'];
                $data['password'] = md5($data['password']);
                $sendCode = Session::get('code');
                $sendPhone = Session::get('tel');
                unset($data['code']);
                //对比验证码
                if ($sendCode == $code && $sendPhone == $phoneNum){
                    $data['registration_time'] = date('Y-m-d H:i:s',time());
                    if (array_key_exists('sign',$data)){
                        unset($data['sign']);
                    }
                    $re = Db::name('user')
                        ->insert($data);
                    if ($re){
                        $result = Config::get('code.success');
                        $result['data']['account'] = $phoneNum;
                    }else{
                        $result = Config::get('code.error');
                    }
                }else{
                    $result = Config::get('code.error');
                    $result['msg'] = "验证码错误";
                }
            }catch (\Exception $ex){
                $result = config('code.miss');
                $result['data'] = [];
            }
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 发送验证码
     * @return array|Json
     */
    public function codeGet(){
        $data = Request::instance()->post();
        if (!empty($data['account']) && !empty($data['type'])){
            $phoneNum = $data['account'];
            if ($data['type'] !=='register' && $data['type'] !=='unregistered'){
                $result = Config::get('code.mistake');
                $result['msg'] = "类型不对";
                return json($result);
            }
            // 判断请求场合
            if ('register' == $data['type']){
                // 注册请求
                $user       = Db::table('user')->where(['account'=>$phoneNum])->count();
                $supplier   = Db::table('supplier')->where('account',$phoneNum)->count();
                if ($user >0){
                    $result = Config::get('code.error');
                    $result['msg'] = "该手机号已注册账号，请使用手机号登录";
                    return json($result);
                }else if($supplier >0){
                   $result = Config::get('code.error');
                    $result['msg'] = "手机号已在商户端注册，不能再次注册";
                    return json($result); 
                }
            }elseif('unregistered' == $data['type']){
                // 已注册请求
                $user = Db::name('user')
                    ->where(['account'=>$phoneNum])
                    ->count();
                if ($user == 0){
                    $result = Config::get('code.error');
                    $result['msg'] = "手机号未注册";
                    return json($result);
                }
            }
            $code = codeRange(6);
            $msmRes = json_decode(SendMsg($phoneNum,$code),true);
            if ('000000' !== $msmRes['code']){
                //发送失败
                $result = Config::get('code.error');
                $result['data']['account'] = $phoneNum;
                $result['data']['code'] = $code;
                $result['msg'] = "发送失败";
            }else{
                Session::set('code',$code);
                Session::set('tel',$phoneNum);
                $result = Config::get('code.success');
                $result['data']['account'] = $phoneNum;
                $result['data']['code'] = $code;
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 用户密码登录
     * @return array|Json
     */
    public function login(){
        $data = Request::instance()->post();
        if (!empty($data['account']) && !empty($data['password']) && !empty($data['type'])){
            // 判断账号是否存在
            $isAccount = Db::name('user')
                ->where(['account'=>$data['account']])
                ->find();
            if(!$isAccount){
                $result = Config::get('code.null');
                $result['msg'] = "用户端账号不存在，请重新填写";
                $result['data'] = $data;
                $result['sql'] = Db::name('user')->getLastsql();
                return json($result);
            }
            // 密码加密
            $data['password'] = md5($data['password']);
            $re = Db::name('user')
                ->where(['account'=>$data['account'],'password'=>$data['password']])
                ->find();
            if ($re){
                // 生成新的token
                if ('APP' == $data['type']){
                    $token['app_token'] = randomNum();
                    $token['device_id'] = $data['device_id'];
                }else if ('WEB' == $data['type']){
                    $token['web_token'] = randomNum();

                }
                db('user')->where(['id'=>$re['id']])->update($token);
                $result = Config::get('code.success');
                $re['app_token'] = $token['app_token'];
                $result['data'] = $re;
                $result['token'] = $token;
            }else{
                $result = Config::get('code.error');
                $result['msg'] = "账号或密码错误";
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

//    /**
//     * @writer:leijie
//     * @DateTime:2018-01-16
//     * @rewriter:xx
//     * @rewriter_date:YY-MM-DD
//     * @description: 设置密码
//     * @return array|Json
//     */
//    public function pwdSet(){
//        $data = Request::instance()->post();
//        if (!empty($data['account']) && !empty($data['password'])){
//            // 默认前端密码已确认2次输入一致
//            $re = Db::name('user')
//                ->where(['account'=>$data['account']])
//                ->setField('password',$data['password']);
//                if ($re){
//                    $result = Config::get('code.success');
//                }else{
//                    $result = Config::get('code.error');
//                }
//        }else{
//            $result = Config::get('code.null');
//        }
//        return json($result);
//    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 完善注册信息
     * @return array|Json
     */
    public function information(){
        $data = Request::instance()->post();
        if(!validate('Rules')->scene('registered')->check($data)){
            $result = config('code.error');
            $result['msg'] = validate('Rules')->getError();
            return json($result);
        }
        if (!empty($data)){
            if (array_key_exists('sign',$data)){
                unset($data['sign']);
            }
            $data['is_complete'] = 1;
            // 加密密码
            $re = Db::name('user')
                ->where(['account'=>$data['account']])
                ->update($data);
            $res = Db::table('user')->where('account',$data['account'])->find();
            if ($re && $res){
                $result = Config::get('code.success');
                $result['data'] = $res;
            }else{
                $result = Config::get('code.mistake');
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 注册选取地址
     * @return array|Json
     */
    public function zipCode(){
        $data = Request::instance()->post();
        if (!empty($data['postcode'])){
            $re = getAreaInfoByCode($data['postcode']);
            if ($re){
                $result = Config::get('code.success');
                $result['data']['list'] = $re;
            }else{
                $result['status']   = 203;
                $result['msg']      = '无效的邮编';
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 验证码登录
     * @return array|Json
     */
    public function codeLogin(){
        $data = Request::instance()->post();
        if (!empty($data['account']) && !empty($data['code']) && !empty($data['type'])){
            $phoneNum = $data['account'];
            // 判断账号是否存在
            $user = Db::name('user')
                ->where(['account'=>$phoneNum])
                ->count();
            if($user==0){
                $result = Config::get('code.null');
                $result['msg'] = "账号不存在，请重新填写";
                return json($result);
            }
            $code = $data['code'];
            $sendCode = Session::get('code');
            $sendPhone = Session::get('tel');

            $re = Db::name('user')
                ->where(['account'=>$phoneNum])
                ->find();
            if ($code == $sendCode && $re && $phoneNum == $sendPhone ){
                // 生成新的token
                if ('APP' == $data['type']){
                    $token['app_token'] = randomNum();
                    $token['device_id'] = $data['device_id'];
                }else if ('WEB' == $data['type']){
                    $token['web_token'] = randomNum();
                }
                db('user')->where(['id'=>$re['id']])->update($token);
                $result = Config::get('code.success');
                $re['app_token'] = $token['app_token'];
                $result['data'] = $re;

            }else{
                $result = Config::get('code.error');
                $result['msg'] = "账号或验证码错误";
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: APP找回密码
     * @return array|Json
     */
    public function pwdRest(){
        $data = Request::instance()->post();
        if (!empty($data['password']) && !empty($data['account']) && !empty($data['code'])){
            $phoneNum = $data['account'];
            $code = $data['code'];
            $sendCode = Session::get('code');
            $sendPhone = Session::get('tel');
            // 检测输入的手机号是否已注册
            $re = Db::name('user')
                ->where(['account'=>$phoneNum])
                ->find();
            if (!$re){
                $result = Config::get('code.error');
                $result['msg'] = "手机号未注册";
                return json($result);
            }
            if ($code == $sendCode && $re && $sendPhone == $phoneNum){
                // 加密密码
                $data['password'] = md5($data['password']);
                if ($re['password'] == $data['password']){
                    $rePwd = true;
                }else{
                    $rePwd = Db::name('user')
                        ->where(['account'=>$phoneNum])
                        ->setField('password',$data['password']);
                }
                if (false !== $rePwd){
                    $result = Config::get('code.success');
                }else{
                    $result = Config::get('code.error');
                }
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    public function defaults(){
        $xhlData = [];
        $xhlData['tel']                = Db::table('system_setting')->where('name','平台电话')->value('value');
        $xhlData['email']              = Db::table('system_setting')->where('name','平台邮箱')->value('value');
        $xhlData['addr']               = Db::table('system_setting')->where('name','地址')->value('value');
        $xhlData['addr_english']       = Db::table('system_setting')->where('name','地址_英文')->value('value');
        $xhlData['manager']            = Db::table('system_setting')->where('name','联系人')->value('value');
        $xhlData['manager_english']    = Db::table('system_setting')->where('name','联系人_英文')->value('value');
        $xhlData['user_content']       = Db::table('protocol')->where('type',1)->value('content');
        if ($xhlData){
            $result['status']     = 200;
            $result['xhlData']    = $xhlData;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }


    public function setUserAvatar(){
        try {
            $user_id = \request()->post('user_id');
            $client = new Oss();
            $re = $client->uploadFile('user', 'img');
            if ($re) {
                Db::name('user')->where('id', $user_id)->update(['image' => $re[0]]);
                $res['status'] = 200;
                $res['msg'] = '上传成功';
                $res['path'] = $re;
            } else {
                $res['status'] = 203;
                $res['msg'] = '上传失败';
            }
        }catch (Exception $e){
            $res['status'] = 203;
            $res['msg'] = '上传失败';
        }
        return json($res);
    }
}